package com.itxuhang.mapping;

import com.itxuhang.handler.QueryUserHandler;
import com.itxuhang.handler.SaveUserHandler;
import com.itxuhang.springframework.aware.BeanFactoryAware;
import com.itxuhang.springframework.factory.BeanFactory;
import com.itxuhang.springframework.factory.DefaultListableBeanFactory;
import com.itxuhang.springframework.init.InitializingBean;
import com.itxuhang.springframework.po.BeanDefinition;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanNameUrlHandlerMapping implements HandlerMapping, BeanFactoryAware, InitializingBean {
    // 存储URL和对应处理类的关系
    private Map<String,Object> urlHandlerMap = new HashMap<>();

    private DefaultListableBeanFactory beanFactory;

    public BeanNameUrlHandlerMapping() {
//        urlHandlerMap.put("/queryUser",new QueryUserHandler());
//        urlHandlerMap.put("/saveUser",new SaveUserHandler());
    }

    @Override
    public void setBeanFactory(DefaultListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Object getHandler(HttpServletRequest request) {
        String uri = request.getRequestURI();
        if (uri == null || "".equals(uri)){
            return null;
        }
        return this.urlHandlerMap.get(uri);
    }

    @Override
    public void afterPropertiesSet() {
        List<BeanDefinition> beanDefinitions = beanFactory.getBeanDefinitions();
        for (BeanDefinition bd : beanDefinitions) {
            String beanName = bd.getBeanName();
            if (beanName == null || "".equals(beanName)){
                continue;
            }
            if (beanName.startsWith("/")){
               this.urlHandlerMap.put(beanName,beanFactory.getBean(beanName)) ;
            }
        }
    }
}
